package org.sang.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.gson.Gson;
import org.sang.bean.MbrCard;
import org.sang.bean.MbrCardExample;
import org.sang.bean.Member;
import org.sang.common.SnowflakeIdGeneratorUtils;
import org.sang.common.UserUtils;
import org.sang.constant.GenderEnum;
import org.sang.constant.MemberTypeEnum;
import org.sang.exception.MemberBaiscException;
import org.sang.mapper.MemberInfoMapper;
import org.sang.mapper.ext.MbrCardExtMapper;
import org.sang.service.IMemberService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.regex.Pattern;

/**
 * The type Member service.
 */
@Service
@Transactional
public class MemberServiceImpl implements IMemberService {

    private static final Logger logger = LoggerFactory.getLogger(MemberServiceImpl.class);
    @Autowired
    private MemberInfoMapper memberInfoMapper;
    @Autowired
    private MbrCardExtMapper mbrCardExtMapper;

    private static final Gson gson = new Gson();
    @Override
    public int add(Member member) {

        int result;
        this.valid(member);
        try {
            member.setMemberType(1);
            member.setCreatedTime(new Date());
            member.setCreatedOperator(UserUtils.getCurrentUser().getUsername());
            member.setUpdateOperator(UserUtils.getCurrentUser().getUsername());
            member.setUpdateTime(new Date());
            member.setId(String.valueOf(SnowflakeIdGeneratorUtils.getId()));
            logger.info("新增会员信息:{}",gson.toJson(member));
            result = memberInfoMapper.save(member);
            //新增会员卡信息
            MbrCard mbrCard = new MbrCard();
            mbrCard.setBalance(0);
            mbrCard.setCardNo(member.getCardNo());
            mbrCard.setStoreId(member.getStoreId());
            mbrCard.setId(String.valueOf(SnowflakeIdGeneratorUtils.getId()));
            //默认有效
            mbrCard.setState("1");
            mbrCard.setCreatedOperator(UserUtils.getCurrentUser().getUsername());
            mbrCard.setUpdateOperator(UserUtils.getCurrentUser().getUsername());
            mbrCard.setCreatedTime(new Date());
            mbrCard.setUpdateTime(new Date());
            mbrCardExtMapper.insert(mbrCard);
            logger.info("新增会员卡信息:{}",gson.toJson(mbrCard));
        } catch (Exception e) {
            e.printStackTrace();
            throw new MemberBaiscException("注册失败!");
        }
        return result;
    }

    /**
     * Valid.
     *
     * @param member the member
     */
    void valid(Member member) {

        //校验手机号
        if (!Pattern.matches("^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|(147))\\d{8}$", member
            .getPhoneNo())) {
            logger.error("手机号非法,{}", member.getPhoneNo());
            throw new MemberBaiscException("注册失败!手机号非法!");
        }

        //校验卡号 纯数字
        if (Pattern.matches("\\d{32}", member.getCardNo())) {
            logger.error("会员卡号非法,{}", member.getCardNo());
            throw new MemberBaiscException("注册失败!会员卡号非法");
        }


        int countByIdNum = memberInfoMapper.getCountMemberByIdNum(member.getIdNum());
        if (countByIdNum > 0) {
            throw new MemberBaiscException("注册失败!身份证号已经存在!");
        }
        int countByCardNo = memberInfoMapper.getCountMemberByCardAndStore(member.getCardNo(), member.getStoreId());
        if (countByCardNo > 0) {
            throw new MemberBaiscException("注册失败!会员卡号已经存在!");
        }
    }

    @Override
    public Member getMemberById(String id) {
        logger.info("获取{}会员信息",id);
        return memberInfoMapper.getMemberById(id);
    }

    @Override
    public int update(Member member, String id) {
        if (!Pattern.matches("^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|(147))\\d{8}$", member
            .getPhoneNo())) {
            logger.error("手机号非法,{}", member.getPhoneNo());
            throw new MemberBaiscException("注册失败!手机号非法!");
        }
        //校验卡号 纯数字
        if (Pattern.matches("\\d{32}", member.getCardNo())) {
            logger.error("会员卡号非法,{}", member.getCardNo());
            throw new MemberBaiscException("注册失败!会员卡号非法");
        }

        int result = 0;
        try {
            member.setUpdateTime(new Date());
            member.setUpdateOperator(UserUtils.getCurrentUser().getUsername());
            result = memberInfoMapper.update(member, id);
            logger.info("更新会员卡信息:{}",gson.toJson(member));
        } catch (Exception e) {
            e.printStackTrace();
            throw new MemberBaiscException("修改用户信息失败");
        }
        return result;
    }

    @Override
    public void delete(String id) {
        try {
            Member member = memberInfoMapper.getMemberById(id);
            MbrCard mbrCard = new MbrCard();
            mbrCard.setCardNo(member.getCardNo());
            mbrCard.setStoreId(member.getStoreId());
            MbrCardExample mbrCardExample = new MbrCardExample();
            mbrCardExample.createCriteria().andCardNoEqualTo(member.getCardNo())
                .andStoreIdEqualTo(member.getStoreId());
            mbrCardExtMapper.deleteByExample(mbrCardExample);
            logger.info("会员:{}，删除关联会员卡:{},门店编号:{}", id, member.getCardNo(), member.getStoreId());
            memberInfoMapper.delete(id);
            logger.info("会员:{}，删除关联会员信息.", id);
        } catch (Exception e) {
            e.printStackTrace();
            throw new MemberBaiscException("删除会员失败!");
        }
    }

    @Override
    public Page<Member> getMemberListByPage(int pageNum, int pageSize, Member member) {
        Page<Member> result = PageHelper.startPage(pageNum, pageSize);
        memberInfoMapper.getMemberByPage(member);
        result.stream().forEach(item -> {
            item.setGenderDesc(GenderEnum.getName(item.getGender()));
            item.setMemberTypeDesc(MemberTypeEnum.getName(item.getMemberType()));
        });
        return result;

    }
}
